$(function(){
	var $tabList=$("#tab_list"),$pagebar=$("#pagebar ul"),$pageInfo=$("#page_info"),
		pageNo=1,pageSize=10,count=0;//初始值
	/**---------------封装分页方法,count:总条目数,pageNo:当前页---------------*/
	function pageit(count){
		$pagebar.empty();
		//首页和上一页
		if(pageNo==1){
			$pagebar.append("<li id='start_page' class='disabled'><a href='javascript:void(0);'>首页</a></li>");
			$pagebar.append("<li id='prev_page'  class='disabled'><a href='javascript:void(0);'>上一页</a></li>");
		}else{
			$pagebar.append("<li id='start_page' pn=1><a href='javascript:void(0);'>首页</a></li>");
			$pagebar.append("<li id='prev_page' pn="+(pageNo-1)+"><a href='javascript:void(0);'>上一页</a></li>");
		}
		var tmp=parseInt(count/10);
		var page_size=count%10==0?(tmp):(tmp+1);//总页数
		//中间数字页
		if(page_size<=5){
			//如果小于5页,则全部显示
			for(var i = 0; i <page_size; i++) {
				if(i==pageNo-1){
					$pagebar.append("<li pn="+(i+1)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
				}else{
					$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
				}
			}
		}else{
			//如果总页数大于5页,显示当前页和前后各两页以及两个...符号
			if(pageNo<3){
				for(var i = 0; i <5; i++) {
					if(i==pageNo-1){
						$pagebar.append("<li pn="+(i+1)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}else{
						$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}
				}
				$pagebar.append("<li class='disabled'><a href='javascript:void(0);'>...</a></li>");
			}else if(pageNo>page_size-2){
				$pagebar.append("<li class='disabled'><a href='javascript:void(0);'>...</a></li>");
				for(var i = page_size-5; i <page_size; i++) {
					if(i==pageNo-1){
						$pagebar.append("<li pn="+(i+1)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}else{
						$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}
				}
			}else{
				for (var i = pageNo-3; i <pageNo+2; i++) {
					if(i==pageNo-1){
						$pagebar.append("<li pn="+(pageNo)+" class='active'><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}else{
						$pagebar.append("<li pn="+(i+1)+"><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
					}
				}
			}
		}
		//下一页和末页
		if(page_size==0||pageNo==page_size){
			$pagebar.append("<li id='next_page' class='disabled'><a href='javascript:void(0);'>下一页</a></li>");
			$pagebar.append("<li id='end_page' class='disabled'><a href='javascript:void(0);'>末页</a></li>");
		}else{
			$pagebar.append("<li id='next_page' pn="+(pageNo+1)+"><a href='javascript:void(0);'>下一页</a></li>");
			$pagebar.append("<li id='end_page' pn="+page_size+"><a href='javascript:void(0);'>末页</a></li>");
		}
		
		//绑定事件
		$pagebar.find("li").not(".disabled").on("click",function(){
			pageNo=parseInt($(this).attr("pn"));//更新当前页码
			reloadList();
		});
		//分页信息条
		$pageInfo.find("span").each(function(i,k){
			if(i==0){
				if(page_size==0){
					$(k).html(0);
				}else{
					$(k).html((pageNo-1)*10+1);
				}
			}else if(i==1){
				$(k).html(count>pageNo*10?pageNo*10:count);
			}else{
				$(k).html(count);
			}
		});
	}
	/**------------------加载列表---------------------*/
	var noRecord= "<font style='color:red;font-weight:bold;font-size:13px;'>无</font>";
	var params={"pageNo":1,"pageSize":pageSize};
	var authStatus = {0:"认证中",1:"<font style='color:green;font-weight:bold;font-size:13px;'>已认证</font>",2:"<font style='color:red;font-weight:bold;font-size:13px;'>认证失败</font>"};
	var delStatus = {0:"<font style='color:green;font-weight:bold;font-size:13px;'>未删除</font> ",1:" <font style='color:red;font-weight:bold;font-size:13px;'>删除</font>"};
	function reloadList(){
		params.pageNo=pageNo;
		params.pageSize=pageSize;
		$.get(serverURL+"view/thesis/getList",params,function(data){
//			data=$.parseJSON(data);
			try {
				if(data.code==0){
					data=data.data;
					$tabList.find("tbody").empty();
					count=data.pagination.totalCount;
					if(count>0){
						var html="";
						$.each(data.list,function(i,k){
							html+="<tr>" +
							"<td id='pkc'><input type='checkbox' id='"+k.thesisId+"' class='checkbox' col='"+i+"' ></td>" +
							"<td>"+((pageNo-1)*10+i+1)+"</td>" +
							"<td><a href=http://ow365.cn/?i=11328&furl=http://www.gongchengjie.cn//"+k.path+" target='_blank'>"+(k.name?k.name:noRecord)+"</a></td>"+ 
							"<td>"+(k.size?k.size:noRecord)+"</td>"+ 
							"<td>"+(k.uploadTime?k.uploadTime:noRecord)+"</td>"+ 
							"<td>"+k.downloadCount+"</td>"+ 
							"<td>"+k.collectionCount+"</td>"+ 
							"<td>"+k.price+"</td>"+ 
							"<td>"+k.commentCount+"</td>"+ 
							"<td>"+k.browseCount+"</td>"+ 
							"<td>"+authStatus[k.authStatus]+"</td>"+ 
							"<td>"+delStatus[k.deleteStatus]+"</td>"+ 
							"</tr>";
						});
						$tabList.find("tbody").append(html);
//						$(".tools button").removeAttr("disabled");
					}else{
						$tabList.find("tbody").append("<tr><td colspan="+$("thead th").length+">无数据</td></tr>");
//						$(".tools button").not(".btn-default").attr("disabled","disabled");
					}
					pageit(count);//重绘工具栏
				}else if(data.code!=-1){
					alert("数据加载出错，请稍后重试");
				}
			} catch (e) {
				alert("数据加载出错，请稍后重试");
			}
		});
	}
	reloadList();
	//全选与取消全选
	$("#pkall").change(function(){
		if($(this).prop("checked")){
			$tabList.find("#pkc :checkbox").prop("checked",true);
		}else{
			$tabList.find("#pkc :checkbox").prop("checked",false);
		}
	});
	//获取选中的行
	function getSelectedCols(){
		return $tabList.find("#pkc :checkbox").filter(":checked");
	}

	/**---------------查询-----------------*/
	$("#btn_search").click(function(){
		params.nickName=$("#search_nickName").val();
		params.phone=$("#search_phone").val();
		pageNo=1;
		reloadList();
		return false;
	});
	/**---------------重置-----------------*/
	$("#btn_reset").click(function(){
		$("#form_search").get(0).reset();
		pageNo=1;
		reloadList();
		return false; 
	});
    
	
	
    /*************添加标签*************/
	function addTag() {
		$.get(serverURL + "view/thesis/label/getList", function(data) {
			try{
				if (data.code == 0) {
					$(".row").empty();
					if (data.data.length > 0) {
						var html = "<select name='' id='jquery-tagbox-select-options' style='width:220px;' placeholder='添加标签' class=‘form-control’ data-toggle=‘tooltip’ data-placement=‘top’ title=‘请选择标签’>";
						
						$.each(data.data, function(i, k) {
							html += "<option  value=" + k.labelId + ">" + k.labelName+ "</option>";
							
						});
						$(".row").html(html+"</select><input type='text' id='jquery-tagbox-select' />");
						
						$("#jquery-tagbox-text").tagBox();
						$("#jquery-tagbox-select").tagBox({
							enableDropdown : true,
							dropdownSource : function() {
								return $("#jquery-tagbox-select-options");
							}
						});
					} else {
						$("#jquery-tagbox-select-options").html("<option>无数据</option>");
					}
				} else if (data.code != -1) {
					alert("数据加载出错，请稍后重试");
				}
			}catch(e){
				
			}
		});
	}
    

	var $formUpload=$("#form_upload");
	var imgReg=/^.+\.(jpg|png|bmp|gif)$/;

	$formUpload.find("[name=file]").change(function(){

		$formUpload.ajaxSubmit({  
			dataType:'json',
			resetForm:true,
	        success:function(data){
	        	if(data.code==0){
	        		$formUpload.find("[name=path]").val(data.data.url);
	        		$formUpload.find("[name=size]").val(data.data.size);
	        	}else{
	        		alert("文件上传失败，请重试");
	        		$formUpload.get(0).reset();
	        	}
	        } 
		});
	});
	
	
    /** ************增加文件*************** */
	var $formAdd=$("#form_add");
    $("#btn_add").click(function(){
    	$("#modal_add").modal("show");
    	addTag();
    	addCategory($formAdd);
    	addType(0);
    });
    
    
	function checkAddForm(){
		if($formUpload.find("[name=path]").val()==""){
			warnInput($("[name=file]"));
			return false;
		}
		if($("[name=name]").val() == ""){
			warnInput($("[name=name]"));
			return false;
		}
		if($("[name=type]").val() == 0){
			warnInput($("[name=type]"));
			return false;
		}
		if($("[name=top]").val() == 0){
			warnInput($("[name=top]"));
			return false;
		}
		if($("[name=second]").val() == 0){
			warnInput($("[name=second]"));
			return false;
		}
		if($("[name=cardinal]").val() == ""){
			warnInput($("[name=cardinal]"));
			return false;
		}
		return true;
	}
	
		/*** 添加论文*/
	 $("#btn_confirm_add").click(function() {
		if (checkAddForm()) {
			if($(".tagBox-list ").find("a").length == 0 ){
				alert("请选择标签");
				return false;
			}
			var labelIds = "";
			$.each($(".tagBox-list ").find("a"), function(i, k) {
				labelIds += k.rel + ",";
			});
			labelIds = labelIds.substring(0, labelIds.length - 1);
			path = $formUpload.find("[name=path]").val();
			size = $formUpload.find("[name=size]").val();
			typeId =$formAdd.find($("[name=type]")).val();
			tcId =$formAdd.find($("[name=top]")).val();
			scId =$formAdd.find($("[name=second]")).val();

			var price = 0;
			if($formAdd.find($("[name=price]")).val() != ""){
				price = $formAdd.find($("[name=price]")).val();
			}
			
			introduction = $("textarea[name='content1']").val();
			$.post(serverURL + "view/thesis/add", {"authStatus":'1',"name" : $("[name=name]").val(),"path" : path,"size" : size,"labelIds" : labelIds,"typeId" : typeId,"tcId" : tcId,"scId" : scId,"introduction":introduction,"price":price}, function(data) {
				if (data.code == 0) {
					alert("添加成功");
					$("#modal_add").modal("hide");
					 $formAdd.get(0).reset();
					 $formUpload.get(0).reset();
					 reloadList();
				} else if (data.code != -1) {
					alert("添加失败,请稍后重试");
				}
			});
		}
	})
	
	/** ***********添加分类********************* */
	function addCategory(object) {
			// 一级分类选择
			var $second = object.find("[name=second]"), 
			$top = object.find("[name=top]");
			$content = object.find("[name=content]"), 
			$projectMode = object.find("[name=project_mode]"), 
	
			$.get("view/thesis/category/getTopCategory", function(data) {
				$.each(data.data, function(i, obj) {
					$top.append("<option value='" + obj.tcId + "'>" + obj.tcName+ "</option>");
				});
			}, "json");
			/*--------------修改的一、二、三级二级联动处理----------------*/
			$top.change(function() {
				districtEdit.reloadSecond($(this).val());
				$content.show();
				$projectMode.show();
				if($(this).val() == 1 ){
					$content.hide();
					$projectMode.hide();
				}
			});
	
			var districtEdit = {
				clearSecond : function() {
					$second.find("option[value!=0]").remove();
				},
				reloadSecond : function(tcId) {
					districtEdit.clearSecond();
					if (tcId != 0) {
						$.ajax({ // 此处用同步处理，避免出现val()比reload早的问题
							url : serverURL + "view/thesis/category/getSecondaryCategory?"+ "tcId=" + tcId,
							type : "get",
							async : false,
							success : function(data) {
								if (data.code == 0) {
									var html = "";
									$.each(data.data, function(i, k) {
										html += "<option value='" + k.scId +"'>"+ k.scName + "</option>";
									});
									$second.append(html);
								} else if (data.code != -1) {
									alert("一二级分类数据加载失败");
								}
							}
						});
					}
				},

			};
		}
	
	/***********添加分类****************/
	function addType(type){
		$.get("view/thesis/type/list", function(data) {
			if(type == 0){
				$formAdd.find("[name=type]").empty();
			}else{
				$formEdit.find("[name=type]").empty();
			}
			$.each(data.data, function(i, obj) {
				if(type == 0){
					$formAdd.find("[name=type]").append("<option value='" + obj.typeId + "'>" + obj.typeName+ "</option>");
				}else {
					var option = "";
					if(type == obj.typeId){
						option +="<option value='" + obj.typeId + "' selected='selected'>" + obj.typeName+ "</option>";
					}else{
						option +="<option value='" + obj.typeId + "'>" + obj.typeName+ "</option>";
					}
					$formEdit.find("[name=type]").append(option);
				}
			});
		}, "json");
	}
	
	/**********编辑********/
	var $formEdit=$("#form_edit");
    $("#btn_edit").click(function() {
		// 获取选中的行
		var $curCol = $tabList.find("#pkc :checkbox").filter(":checked");
		if ($curCol.length != 1) {
			alert("请选择一条记录预览");
			return;
		}
		var id = $curCol[0].id;
		$.get("view/thesis/getInfo",{"fileId":id}, function(data) {

//			alert(data.data.name);
			$formEdit.find("[name=name]").val(data.data.name);
			addType(data.data.typeId);
			addCategory($formEdit,data.data.tcId,data.data.scId);
		});
		$("#modal_edit").modal("show");
	});
	
	/***************查看详情********************/
    $("#btn_scan").click(function() {
		// 获取选中的行
		var $curCol = $tabList.find("#pkc :checkbox").filter(":checked");
		if ($curCol.length != 1) {
			alert("请选择一条记录预览");
			return;
		}
		var id = $curCol[0].id;
//		alert(id);
		window.location.href="thesis/tiaozhuan.htm?thesisId="+id;
		//$("#modal_scan").modal("show");
	});	
	
	/**************删除************/
	$("#btn_del").click(function(){
		var $curCol = $tabList.find("#pkc :checkbox").filter(":checked");
		if ($curCol.length == 0) {
			alert("请至少选择一条记录删除");
			return;
		}
		var ids = "";
		$.each($curCol, function(i, k) {
			ids += $curCol[i].id + ",";
		})
		ids = ids.substring(0, ids.length - 1);
		$.get(serverURL + "view/thesis/del", {"ids" : ids}, function(data) {
			if (data.code == 0) {
				alert("删除成功");
				pageNo=1;
				reloadList();
			} else if (data.code != -1) {
				alert("删除失败,请稍后重试");
			}
		});
	});
	
	/*****************认证********************/
	$("#btn_status button").click(function(){
		$("#btn_status button").removeClass("active");
		$(this).addClass("active");
		var $curCol = $tabList.find("#pkc :checkbox").filter(":checked");
		if ($curCol.length == 0) {
			alert("请至少选择一条认证记录");
			return;
		}
		var ids = "";
		$.each($curCol, function(i, k) {
			ids += $curCol[i].id + ",";
		})
		ids = ids.substring(0, ids.length - 1);

		var authStates = $(this).attr("id");
		$.get(serverURL + "view/thesis/auth", {"ids" : ids,"authStatus":authStates}, function(data) {
			if (data.code == 0) {
				pageNo=1;
				reloadList();
			} else if (data.code != -1) {
				alert("删除失败,请稍后重试");
			}
		});
		
	});
	
});